import asyncio
import aiohttp
import json
import datetime
import requests

today = datetime.date.today()
oneday1 = datetime.timedelta(days=2)
yesterday1 = today - oneday1
oneday2 = datetime.timedelta(days=32)
yesterday2 = today - oneday2


class Green:
    def __init__(self):
        self.list01 = []
        # self.list02 = []


    def jim(self):

        responses = requests.get(url, headers=header).json()
        for i in responses['parentResult']:
            id = i['id']
            sellerName = i['sellerName']
            # print(id, sellerName)
            if sellerName != 'WSZCH':
                url01 = 'https://www.4kmiles.com/api2/api/Product/GetParentAsinPageList?queryParam.accountId={}&pagination.rowsPerPage=100&pagination.currentPage=1&queryParam.IsListingView=true&queryParam.startDate={}&queryParam.endDate={}&queryParam.stockStatus=InStock&pagination.sortField=TodayOrders&pagination.sortType=desc'.format(
                    id, yesterday2, yesterday1)
                # print('sellerName',sellerName,'id',id)
                url01_id = (url01, id)
                self.list01.append(url01_id)

        return self.list01

    async def jim01(self, i, j):
        csv = open('./xiecheng.csv', 'w', encoding='utf-8')
        # print('i',i)
        async with aiohttp.ClientSession() as session:
            async with session.get(i, headers=header) as responses:
                responses = await responses.json()
                num01 = responses['result']['totalCount']

                print('responses', type(num01),num01)
                await self.jim02(num01, j,csv)
                await asyncio.sleep(1)

    async def jim02(self, num01, i_id,csv):

        if num01 % 100 != 0:
            num02 = int(num01 / 100) + 1

            for i in range(1, num02 + 1):
                url02 = f'https://www.4kmiles.com/api2/api/Product/GetParentAsinPageList?queryParam.accountId={i_id}&pagination.rowsPerPage=100&pagination.currentPage={i}&queryParam.IsListingView=true&queryParam.startDate={yesterday1}&queryParam.endDate={yesterday1}&queryParam.stockStatus=InStock&pagination.sortField=TodayOrders&pagination.sortType=desc'
                await self.jim03(url02,csv)

        else:
            num02 = int(num01 / 100)

            for i in range(1, num02 + 1):
                url02 = f'https://www.4kmiles.com/api2/api/Product/GetParentAsinPageList?queryParam.accountId={i_id}&pagination.rowsPerPage=100&pagination.currentPage={i}&queryParam.IsListingView=true&queryParam.startDate={yesterday1}&queryParam.endDate={yesterday1}&queryParam.stockStatus=InStock&pagination.sortField=TodayOrders&pagination.sortType=desc'
                await self.jim03(url02,csv)

    async def jim03(self, url02,csv):
        async with aiohttp.ClientSession() as session:
            async with session.get(url02, headers=header) as responses:
                responses = await responses.json()
                print('responses', responses['result']['data'])
                for j in responses['result']['data']:
                    print(j)

                    csv.write(str(j))

                    print('-' * 10)


url = 'https://www.4kmiles.com/api2/api/SellerAccount/GetCurrentUserSellerAccountList'
header = {
    'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIzMyIsImNyZWF0ZWQiOjE2MjkxODU0OTMyNjcsImRldGFpbCI6eyJ1c2VySWQiOjMzLCJsb2dpblVzZXJOYW1lIjoibzQ4XzBtYndmb3V6ekBkaW5ndGFsay5jb20iLCJ1c2VyQWNjb3VudFR5cGUiOjIsImxvZ2luVXNlcklkIjoyODAwNTQ3LCJ1c2VybmFtZSI6IjMzIiwicGFzc3dvcmQiOiJBRDBORlRJejgxTkdXWElpWmZGbHA2ZFNKdnNUWkRFNHBuTGQ5dzFONHdJWEdQQ0l3SFlYQkFod0c0QlVyQmlMWEE9PSIsImNoYW5uZWxUeXBlIjowfSwiZXhwIjoxNjI5NzkwMjkzfQ.V7m164M5JY9YrntYgfFgI4OzAIAKge90JRKDvN-52L83FiAbJS4Ol4M6dzn3rz750pDE3b1eIBFkVr-X-_kRTw',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
}
mokie = Green()

# mokie.jim()
tasks = [asyncio.ensure_future(mokie.jim01(i[0], i[1])) for i in mokie.jim()]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
